package log

import (
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/sirupsen/logrus"
	"strings"
	"time"
)

type Conf struct {
	Output     string //输出目录
	FileName   string //输出文件   "battle"
	FileSuffix string //文件后前缀 "-%Y%m%d%H%M" "abc-%Y-%m-%d/%H-%M"
	FileExt    string //文件扩展名 ".log"
	Format     string // json or txt ,,""=> txt
	MaxLogSize int64  //分割文件的大小
	RotateTime int    //每隔多长秒数生成新日志文件 3600 为一小时
	MaxAge     int    //最大保留秒数	3600*24=86400 为一天 3600*24*7=604800 为一周 3600*24*30=2592000 为一30天 3600*24*365=31536000 为一年
}

type AgLogger struct {
	Logger *logrus.Logger
}

var loggerGlobal *AgLogger

func init() {

}

func NewLog(conf *Conf) (*AgLogger, error) {
	writer, err := rotatelogs.New(
		conf.Output+conf.FileName+conf.FileSuffix+conf.FileExt,
		rotatelogs.WithLinkName(conf.Output+conf.FileName+conf.FileExt),
		rotatelogs.WithMaxAge(time.Duration(conf.MaxAge)*time.Second),
		rotatelogs.WithRotationTime(time.Duration(conf.RotateTime)*time.Second),
		rotatelogs.WithRotationSize(conf.MaxLogSize),
	)
	if err != nil {
		return nil, err
	}
	logger := logrus.New()
	logger.SetOutput(writer)
	lowerFormat := strings.ToLower(conf.Format)
	if lowerFormat == "" || strings.Compare(lowerFormat, "txt") == 0 || strings.Compare(lowerFormat, "text") == 0 {
		logger.SetFormatter(&logrus.TextFormatter{})
	} else if strings.Compare(lowerFormat, "json") == 0 {
		logger.SetFormatter(&logrus.JSONFormatter{})
	}
	outputLog := &AgLogger{
		Logger: logger,
	}
	if loggerGlobal == nil {
		loggerGlobal = outputLog
	}
	return outputLog, nil
}

func Logger() *AgLogger {
	return loggerGlobal
}

func Trace(args ...interface{}) {
	loggerGlobal.Trace(args...)
}
func Info(args ...interface{}) {
	loggerGlobal.Info(args...)
}
func Debug(args ...interface{}) {
	loggerGlobal.Debug(args...)
}

func Error(args ...interface{}) {
	loggerGlobal.Error(args...)
}
func Warn(args ...interface{}) {
	loggerGlobal.Error(args...)
}
func Fatal(args ...interface{}) {
	loggerGlobal.Fatal(args...)
}

func Panic(args ...interface{}) {
	loggerGlobal.Panic(args...)
}

func (logger *AgLogger) Trace(args ...interface{}) {
	logger.Logger.Trace(args...)
}
func (logger *AgLogger) Debug(args ...interface{}) {
	logger.Logger.Debug(args...)
}
func (logger *AgLogger) Info(args ...interface{}) {
	logger.Logger.Info(args...)
}

func (logger *AgLogger) Error(args ...interface{}) {
	logger.Logger.Error(args...)
}
func (logger *AgLogger) Warn(args ...interface{}) {
	logger.Logger.Warn(args...)
}
func (logger *AgLogger) Fatal(args ...interface{}) {
	logger.Logger.Fatal(args...)
}
func (logger *AgLogger) Panic(args ...interface{}) {
	logger.Logger.Panic(args...)
}
